import { success, fail } from "../utils/base";
import { getTimestampToType } from "../utils/time";
import {
  getBDCConfig,
  getOtherDbData,
  cleanExpiredData,
} from "../utils/lokijs-db-server";

// 默认查询-时间范围
let defaultInfoTime = 3;

/**
 * @description: 这里查询日志
 * 1. 分页查询
 * 2. 默认时间范围: 最近 3 天
 * 3. 查询 某个路由的 pv 曝光量
 * 4.
 */
export default defineEventHandler(async (event) => {
  // 获取请求参数 post
  const body = await readBody(event);
  // 1. 读取配置文件
  const { configData, configPath } = getBDCConfig();

  // 2. 校验参数的正确性
  if (!body.pageNumber || !body.pageSize) {
    return fail(`pageNumber,pageSize参数错误`);
  }
  // 3. 获取 LokiJS 实例
  const db = event.context.db;
  console.log("💾 当前使用的数据库名称:", db.filename);

  let instanceList: any = [];
  let dbCurConfig: any = {}; // 当前实例的配置
  if (configData.dbs && configData.dbs.length > 0) {
    configData.dbs.forEach((e: any) => {
      if (e.path != db.filename) {
        instanceList.push(e);
        console.log("3.1 查询数据库:", e.path);
      } else {
        dbCurConfig = e;
      }
    });
  }

  // 读取文件数据
  if (db) {
    const pagePuv = db.getCollection("pagePuv");
    if (pagePuv === null) {
      db.addCollection("pagePuv");
      return fail("pagePuv 集合不存在,开始初始化数据");
    } else {
      cleanExpiredData(pagePuv);
    }

    let puvData = JSON.parse(JSON.stringify(pagePuv));
    puvData.data = puvData.data.map((el: any) => {
      el.dbName = db.filename;
      return el;
    });
    let total = puvData.data.length;
    // console.log("total: ", total);

    // 获取其他数据源
    const { data: otherDatas } = (await getOtherDbData(
      instanceList,
      "pagePuv"
    )) as any;

    let totalData = puvData.data.concat(otherDatas);

    const dataFilter = (val: any) => {
      let daData = val;
      // 时间倒序
      if (daData.length > 2) {
        daData = daData.sort((a: any, b: any) => {
          a.startTimeStr = formatDate(new Date(Number(a.data.startTime)));
          a.trackTimeStr = formatDate(new Date(Number(a.data.trackTime)));
          if (!a.dbName) a.dbName = db.filename;
          return b.data.startTime - a.data.startTime;
        });
      }

      // 根据时间范围-过滤
      let beginTime = body.beginTime;
      let endTime = body.endTime;
      if (!beginTime) {
        beginTime = Date.now() - defaultInfoTime * 24 * 60 * 60 * 1000;
      }
      if (!endTime) {
        endTime = Date.now();
      }

      daData = daData.filter((e: any) => {
        return e.data.trackTime >= beginTime && e.data.trackTime <= endTime;
      });
      total = daData.length;

      // 根据 path 页面路由,来查找数据源
      //  pv 曝光量
      if (body.path) {
        // zhj-all 查询所有数据
        if (body.path != "zhj-all") {
          daData = daData.filter((e: any) => {
            if (e.data.cusData && e.data.cusData.to && e.data.cusData.to.path) {
              let u = e.data.cusData.to.path;

              if (process.env.NODE_ENV == "development") {
                u = "/fx" + u;
              }
              const regex = /^\/[^/]+\/[^/]+(\/.*)$/; // 匹配前两个路径段，捕获后面的部分
              const match = u.match(regex);
              // console.log(match, "daData:", u);
              if (match && match[1] && match[1] == body.path) {
                return true;
              } else {
                return false;
              }
            }
            return false;
          });
        }

        // 统计类型如果是: UV, 则需要去重
        if (body.statisticalType && body.statisticalType == "UV") {
          const dataMap = new Map(
            daData.map((item: any) => [item.authInfo.trackerId, item])
          );
          // 将 Map 转换回数组（如果需要）
          daData = Array.from(dataMap.values());
        }
        total = daData.length;
      }
      console.log("daData 有多少条:", total);

      // 根据统计粒度, 小时
      let pointInfo: any = {}; // key 时间戳   value pv数量
      if (body.granularity) {
        if (body.granularity == "hour") {
          // 获取每个小时的整点时间戳
          const hours = getTimestampToType(beginTime, endTime) || [];
          // 遍历,查找数量
          daData.forEach((e: any) => {
            const key = hours.findIndex(
              (t) => Number(e.data.trackTime) <= Number(t)
            );

            if (hours[key]) {
              if (pointInfo[`${hours[key]}`]) {
                pointInfo[`${hours[key]}`] += 1;
              } else {
                pointInfo[`${hours[key]}`] = 1;
              }
            }
          });
        } else if (body.granularity == "day") {
          // 获取最近 x 个月,每天 23 点 59 分 59 秒的时间戳
          const months = getTimestampToType(beginTime, endTime, 24) || [];
          // console.log("months", months);
          // 遍历,查找数量
          daData.forEach((e: any) => {
            const key = months.findIndex((t) => e.data.trackTime <= t);
            if (months[key]) {
              if (pointInfo[`${months[key]}`]) {
                pointInfo[`${months[key]}`] += 1;
              } else {
                pointInfo[`${months[key]}`] = 1;
              }
            }
          });
        }
      }

      // 根据 errorId 过滤
      // if (body.errorId) {
      //   daData = daData.filter((e: any) => {
      //     return e.data.errorId == body.errorId;
      //   });
      //   fileData.total = daData.length;
      // }

      if (daData && daData.length > 0) {
        if (daData.length > (body.pageNumber - 1) * body.pageSize) {
          const results = daData.slice(
            (body.pageNumber - 1) * body.pageSize,
            body.pageNumber * body.pageSize
          );
          return success({
            total: total,
            list: results,
          });
        } else {
          return success({
            list: [],
            total: total,
          });
        }
      } else {
        return success({
          list: [],
          total: total,
          statistics: [],
        });
      }
    };

    return dataFilter(totalData);
  } else {
    return fail("db 实例为初始化,数据为空");
  }
});
